package com.duo.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.duo.constant.StatusConstant;
import com.duo.dto.DishPageQueryDTO;
import com.duo.entity.Dish;
import com.duo.entity.DishFlavor;
import com.duo.mapper.DishFlavorMapper;
import com.duo.result.BaseResult;
import com.duo.result.PageResult;
import com.duo.service.DishService;
import com.duo.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    /**
     * 分页查询菜品
     * @return
     */
    @PostMapping("/page")
    public Object list(@RequestBody @Valid DishPageQueryDTO dishPageQueryDTO) {
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return BaseResult.success("菜品分页查询成功", pageResult);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list/{categoryId}")
    public Object list(@PathVariable("categoryId") Long categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getStatus, StatusConstant.ENABLE);
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        List<Dish> list = dishService.list(queryWrapper);
        List<DishVO> result = new ArrayList<>();
        list.forEach(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setDishId(dish.getId());
            LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
            flavorWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(flavorWrapper);
            dishVO.setFlavors(dishFlavors);
            result.add(dishVO);
        });
        return BaseResult.success("获取成功", list);
    }

}
